<template>
	<div class="login">
		<h1>登录</h1>
		<form @submit.prevent="handleLogin">
			<div class="form-group">
				<label for="loginName">用户名:</label>
				<input type="text" id="loginName" v-model="LoginForm.loginName" required />
			</div>
			<div class="form-group">
				<label for="password">密码:</label>
				<input type="password" id="password" v-model="LoginForm.password" required />
			</div>
			<button type="submit">登录</button>
			<router-link to="/register" class="register-link">&nbsp;&nbsp;&nbsp;&nbsp;注册</router-link>
		</form>
	</div>
</template>

<script>
	import Cookies from "js-cookie";
	export default {

		data() {
			return {
				LoginForm: {
					loginName: '',
					password: ''
				}
			}
		}, //当打开登录页面的时候，检查cookie中是否有登录信息，如果有则自动发起登录请求
		created() {
			const loginName = Cookies.get("loginName");
			const password = Cookies.get("password");
			if (loginName != null && loginName != "" && password != null && password != "") {
				this.LoginForm.loginName = loginName;
				this.LoginForm.password = password;
				this.handleLogin();

			}

		},
		methods: {
			handleLogin() {
				// 处理登录逻辑
				let _this = this;
				this.$axios.post('/user/login', {

						username: this.LoginForm.loginName,
						password: this.LoginForm.password

					})
					.then(function(response) {
						if (response.data) {
							// console.log(response)
							sessionStorage.setItem("token", response.data.token);
							Cookies.set("loginName",_this.LoginForm.loginName,{expires:30});
							Cookies.set("password",_this.LoginForm.password,{expires:30});
							// console.log(response.data.token)
							_this.$router.push("/main")

						} else {
							alert("对不起，用户名或密码错误")
						}
					})
					.catch(function(error) {
						console.log(error);
					});
			}
		}
	}
</script>

<style scoped>
	.login {
		max-width: 400px;
		margin: auto;
		padding: 20px;
		background-color: #f9f9f9;
		/* 背景颜色 */
		border-radius: 8px;
		/* 圆角 */
		box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
		/* 阴影效果 */
	}

	h1 {
		text-align: center;
		color: #333;
		/* 标题颜色 */
	}

	.form-group {
		display: flex;
		flex-direction: column;
		margin-bottom: 15px;
		/* 每个输入框之间的间距 */
	}

	label {
		margin-bottom: 5px;
	}

	input {
		padding: 10px;
		border: 1px solid #ccc;
		border-radius: 4px;
	}

	button {
		padding: 10px;
		background-color: #42b983;
		/* 按钮背景颜色 */
		color: white;
		/* 按钮文字颜色 */
		border: none;
		border-radius: 4px;
		cursor: pointer;
	}

	button:hover {
		background-color: #36a76a;
		/* 按钮悬停效果 */
	}

	.register-link {
		display: inline-block;
		margin-top: 10px;
		/* 上边距 */
		color: #42b983;
		/* 链接颜色 */
		text-decoration: none;
		/* 去掉下划线 */
	}

	.register-link:hover {
		text-decoration: underline;
		/* 悬停时添加下划线 */
	}
</style>
